<template>
<div class="item-one" ref="itemOne">
    <div class="title">
      <span>广告素材</span>
      <div>
        <el-button type="primary" @click="vis = true">上传素材</el-button>
      </div>
    </div>
    <div class="container">
      <div class="screeningBox">
        <div class="leftBox">
          <div class="leftitem">
              <!-- <el-input class="merchants1" placeholder="服务商名称" @keyup.enter.native='soso' v-model="service_id"></el-input> -->
              <el-autocomplete class="merchants1" v-model.trim="agentname" :fetch-suggestions="querySearch_fws" @select="serviceid_fws" placeholder="请输入服务商名称" :trigger-on-focus="false"></el-autocomplete>
          </div>
          <div class="leftitem">
            <el-select class="servicelevel" placeholder="广告类型" v-model="AD_type">
                <!-- <el-option keys="1" label="自定义" value="1"></el-option> -->
                <el-option keys="2" label="外部链接" value="2"></el-option>
                <el-option keys="2" label="图片" value="3"></el-option>
                <el-option keys="2" label="视频" value="4"></el-option>
            </el-select>
            <el-input class="BDname" placeholder="素材编号" @keyup.enter.native='soso' v-model.trim="material_num"></el-input>
          </div>
        </div>
        <div class="rightBox">
          <div class="rightitem">
              <el-input class="merchants1" placeholder="素材名称" @keyup.enter.native='soso' v-model.trim="materialName"></el-input>
          </div>
          <div class="rightitem">
            <div class="block">
              <el-date-picker
                v-model="date"
                type="datetimerange"
                value-format="yyyy-MM-dd HH:mm:ss"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
              ></el-date-picker>
            </div>
          </div>
          <div class="rightitem">
            <el-button icon="el-icon-search" type="primary" @click="soso">搜索</el-button>
            <el-button icon="el-icon-refresh" type="primary" @click="reset">重置</el-button>
          </div>
        </div>
      </div>

      <div class="tableBox">
        <el-table
          ref="multipleTable"
          tooltip-effect="dark"
          style="width: 100%"
          :data="tableData"
          :header-cell-style="tableHeaderColor"
        >
          <el-table-column prop="materialNo" align="center" label="素材编号"></el-table-column>
          <el-table-column prop="name" align="center" label="素材名称"></el-table-column>
          <el-table-column align="center" label="素材类型">
            <template slot-scope="scope">
              <span v-if="scope.row.type == 1">自定义</span>
              <span v-if="scope.row.type == 2">外部链接</span>
              <span v-if="scope.row.type == 3">图片</span>
              <span v-if="scope.row.type == 4">视频</span>
            </template>
          </el-table-column>
          <el-table-column prop="agentName" align="center" label="所属服务商"></el-table-column>
          <el-table-column prop="createTime" align="center" label="创建时间"></el-table-column>
          <!-- <el-table-column prop="lastUpdateTime" align="center" label="更新时间"></el-table-column> -->
          <el-table-column align="center" label="URL预览">
            <template slot-scope="scope">
              <a class="a_link" :href="scope.row.url" type="success" target="_Blank">{{scope.row.url}}</a>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="120">
            <template slot-scope="scope">
              <el-button type="text" @click="delMaterial(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            @current-change="handleCurrentChange"
            @size-change="sizechange"
            :page-sizes="[10,20,30,40,50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="combined"
            :current-page.sync="cur_page"
          ></el-pagination>
        </div>
      </div>
      <!-- 上传素材 -->
      <el-dialog v-dialogDrag title="上传素材" :visible.sync="vis" width="45%" :close-on-click-modal="false">
        <el-form
          status-icon
          ref="facility"
          label-width="150px"
          class="demo-dynamic wid90"
        >
          <el-form-item label="素材名称：">
            <el-input type="text" placeholder="请输入素材名称" v-model.trim="material_name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="素材类型：">
            <el-select class="wid100" placeholder="请选择素材类型" v-model="material_type" @change="show()">
              <!-- <el-option keys="1" label="自定义" value="1"></el-option> -->
              <el-option keys="2" label="外部链接" value="2"></el-option>
              <el-option keys="2" label="图片" value="3"></el-option>
              <el-option keys="2" label="视频" value="4"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属服务商：">
            <el-autocomplete class="wid100" v-model.trim="agentname_sc" :fetch-suggestions="querySearch" @select="serviceid" placeholder="非必填，请输入所属服务商" :trigger-on-focus="false"></el-autocomplete>
          </el-form-item>
          <el-form-item label="素材地址：">
            <el-input type="text" class="wid80" v-model.trim="material_URL" :disabled="url_show" placeholder="请输入素材URL" autocomplete="off" onkeyup="this.value=this.value.replace(/[\u4e00-\u9fa5]/ig,'')" ></el-input>
            <el-upload
              class="upload-demo"
              :action="url"
              :headers="token"
              :show-file-list="false"
              :on-success="uploadExcel">
            </el-upload>
            <el-upload
              class="upload-demo1"
              :action="url"
              :headers="token"
              :show-file-list="false"
              :on-success="uploadExcel">
            </el-upload>
            <el-button type="text" class="excelBtn" @click="btnClick()" v-show="material_type == 3">上传图片</el-button>
            <el-button type="text" class="excelBtn" @click="btnClick1()" v-show="material_type == 4">上传视频</el-button>
          </el-form-item>
            <el-form-item label="跳转地址：" v-if="material_type == 1">
            <el-input type="text" v-model.trim="redirectUrl"  placeholder="请输入跳转URL" autocomplete="off" onkeyup="this.value=this.value.replace(/[\u4e00-\u9fa5]/ig,'')" ></el-input>
            
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="vis = false">取消</el-button>
          <el-button type="primary" @click="upMaterial">确定</el-button>
        </span>
      </el-dialog>
      <br>
      <br>
    </div>
</div>
</template>

<script>
import {agent, postAdMaterial, getAdMaterialPage, postAdMaterialDelete} from "@/api/api";
export default {
    name: 'markdown',
    data: function(){
        return {
            url:  this.$store.state.urlexcel +'/product/product/v31/api/merchant/uploadfile/ad/upload',
            token: { token: sessionStorage.getItem("token") },
            service_id:'',//服务商名称/编号
            agentname:'',
            agent_id:'',
            AD_type:'',//广告类型
            material_num:'',//素材编号
            materialName:'',//素材名称
            date:[],//时间
            tableData:[],//列表数据
            combined:0,//列表总条数
            cur_page: 1,
            cur_size: 10,
            vis:false,

            material_name:'',//素材名称
            material_type:'',//素材类型
            agentname_sc:'',//上传素材 服务商模糊查询
            agentname_id:'',
            material_URL:'',//素材地址
            redirectUrl: '',//跳转地址
            agenList:[],
            url_show: false,//控制URL地址是否禁用

            dynamicTags: [],
            inputVisible: false,
            inputValue: ''
        }
    },
    created(){
      this.getAdMaterialPage()
    },
    methods:{
        //修改thead 背景色
        tableHeaderColor({ row, column, rowIndex, columnIndex }) {
            if (rowIndex === 0) {
                return "background-color: #F0F0F0;font-weight: 500;font-size:14px;color:#000;";
            }
        },
        // 分页导航
        handleCurrentChange(val) {
            this.cur_page = val;
            this.getAdMaterialPage()
        },
        // 分页数量
        sizechange(val) {
            this.cur_size = val;
            this.getAdMaterialPage()
        },
        // 搜索
        soso() {
          this.cur_page = 1
          this.getAdMaterialPage()
        },
        //  重置
        reset() {
          this.agentname = ''
          this.agent_id = ''
          this.AD_title = ''
          this.materialName = ''
          this.AD_type = ''
          this.material_num = ''
          this.date = []
        },
        //获取列表数据
        getAdMaterialPage(){
          getAdMaterialPage({
            agentId: this.agent_id,
            title: this.AD_title,
            name: this.materialName,
            type: this.AD_type,
            materialNo: this.material_num,
            startTime: this.date[0],
            finishTime: this.date[1],
            page: this.cur_page,
            size: this.cur_size
          }).then(res => {
            if(res.code ==405){
              sessionStorage.removeItem("token");
              this.$router.push("/login");
            }else if (res.code == 200) {
              this.tableData = res.data
              this.combined = res.pageInfo.recordCount
            }else if(res.code == 500){
              this.$message.error(res.message);
            }
          })
        },
        show(){
          console.log(this.material_type)
          if(this.material_type == 3 || this.material_type == 4){
            this.url_show = true
          }else if(this.material_type == 1 || this.material_type == 2){
            this.url_show = false
            this.material_URL = ''
          }
        },
        querySearch_fws(queryString,cb){
          let that = this
          agent({
            page: 1,
            size: 20,
            keywords: this.agentname
          }).then(res => {
            if(res.code == 405){
              sessionStorage. removeItem('token')
              that.$router.push('/login');
            }else if(res.code == 200){
              that.agenList = []
              for(var i=0;i<res.data.length;i++){
                that.agenList.push({'value':res.data[i].agentname,'id':res.data[i].id})
              }
              let servicearr = that.agenList;
              let results = queryString
                ? servicearr.filter(that.createFilter(queryString))
                : servicearr;
              // 调用 callback 返回建议列表的数据
              cb(results);
            }else{
              that.$message.error(res.message);
            }
          })
        },
        serviceid_fws(item){
          this.agent_id = item.id
        },
        //服务商模糊
        querySearch(queryString,cb){
          let that = this
          agent({
            page: 1,
            size: 20,
            keywords: this.agentname_sc
          }).then(res => {
            if(res.code == 405){
              sessionStorage. removeItem('token')
              that.$router.push('/login');
            }else if(res.code == 200){
              that.agenList = []
              for(var i=0;i<res.data.length;i++){
                that.agenList.push({'value':res.data[i].agentname,'id':res.data[i].id})
              }
              let servicearr = that.agenList;
              let results = queryString
                ? servicearr.filter(that.createFilter(queryString))
                : servicearr;
              // 调用 callback 返回建议列表的数据
              cb(results);
            }else{
              that.$message.error(res.message);
            }
          })
        },
        createFilter(queryString) {
          return restaurant => {
            return (
              restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) !==
              -1
            );
          };
        },
        serviceid(item){
          this.agentname_id = item.id
        },
        btnClick() {
          document.querySelector(".upload-demo .el-upload__input").click();
        },
        btnClick1() {
          document.querySelector(".upload-demo1 .el-upload__input").click();
        },
        uploadExcel(res, file){
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          if(res.code ==405){
            loading.close();
            sessionStorage.removeItem("token");
            this.$router.push("/login");
          }else if (res.code == 200) {
            loading.close();
            this.material_URL = res.data.filePath
            this.$message({
              message: res.message,
              type: "success"
            });
          }else if(res.code == 500){
            loading.close();
            this.$message.error(res.message);
          }
        },
        //上传素材
        upMaterial(){
          if(this.material_name == ''||this.material_name.split(" ").join("").length === 0){
            this.$message.error('素材名称不能为空');
            return false
          }else if(this.material_URL == ''||this.material_URL.split(" ").join("").length === 0){
            this.$message.error('素材地址不能为空');
            return false
          }else if(this.material_URL.length > 255){
            this.$message.error('链接长度不能超过255个字符');
            return false
          }
          postAdMaterial({
            name: this.material_name,
            type: this.material_type,
            agentId: this.agentname_id,
            url: this.material_URL,
            redirectUrl: this.redirectUrl
          }).then(res => {
            if(res.code ==405){
              sessionStorage.removeItem("token");
              this.$router.push("/login");
            }else if (res.code == 200) {
              this.vis = false
              this.getAdMaterialPage()
              this.material_name = ''
              this.material_type = ''
              this.agentname = ''
              this.agentname_id = ''
              this.material_URL = ''
              this.agentname_sc = ''
              this.redirectUrl = ''
              this.$message({
                message: res.message,
                type: "success"
              });
            }else if(res.code == 500){
              this.$message.error(res.message);
            }
          })
        },
        //删除素材
        delMaterial(v){
          this.$confirm(`是否确定删除该条素材？`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
          }).then(() => {
              postAdMaterialDelete({},v).then(res => {
                if(res.code == 405){
                  sessionStorage.removeItem('token')
                  this.$router.push('/login');
                }else if(res.code == 200){
                  this.$message({
                    message: res.message,
                    type: 'success'
                  });
                  this.getAdMaterialPage()
                }else if(res.code == 500){
                  this.$message.error(res.message);
                }
              })
          }).catch(() => {
              this.$message({
                  type: "info",
                  message: "已取消"
              });
          });
        },
    }
}
</script>

<style scoped lang='less'>
.title {
  background: #fff;
  padding: 10px 10px;
  font-size: 18px;
  font-weight: 500;
  display: flex;
  justify-content: space-between;
}
.name {
  width: 25%;
}
.screeningBox {
  width: 100%;
  display: flex;
}
.leftBox,
.rightBox {
  width: 50%;
  padding: 0 15px;
  box-sizing: border-box;
}
.leftBox > .leftitem {
  margin-bottom: 15px;
}
.rightBox > .rightitem {
  margin-bottom: 15px;
}
.merchants {
  width: 40%;
}
.merchants1{
  width: 80%;
}
.tableBox {
  margin-top: 20px;
}
.servicename {
  width: 20%;
}
.servicelevel {
  width: 40%;
}
.width20 {
  width: 20%;
}
.red {
  color: #f9607d;
}
.blue {
  color: #01aaef;
}
.stitle {
  padding: 5px 0;
  font-size: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  i {
    margin-left: 10px;
    margin-right: 5px;
  }
  .swarning {
    color: red;
  }
  .warning {
    color: #f9607d;
  }
}
.wid80{
  width: 80% !important;
}
.wid90{
  width: 90% !important;
}
.wid100{
  width: 100% !important;
}
.wid50{
  width: 50% !important;
}
.upload-demo {
  display: none !important;
}
.upload-demo1 {
  display: none !important;
}
.excelBtn {
  margin-left: 10px;
}
.BDname{
  width: 40%;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 180px;
  margin-left: 10px;
  vertical-align: bottom;
}
.a_link{
  color: #8BC34A;
}
</style>

